package la.iok.hzsvn.lewin.movie.operation.service;

import la.iok.hzsvn.lewin.movie.core.Token;
import la.iok.hzsvn.lewin.movie.operation.model.BalanceTotal;
import la.iok.hzsvn.share.annotations.NotNull;
import la.iok.hzsvn.share.tools.datetime.DateTimeUtil;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class BalanceServiceImpl implements BalanceService{
    private final ChargeOrderService chargeOrderService;
    private final PlayRecordService playRecordService;

    public BalanceServiceImpl(ChargeOrderService chargeOrderService, PlayRecordService playRecordService) {
        this.chargeOrderService = chargeOrderService;
        this.playRecordService = playRecordService;
    }

    @Override
    public BalanceTotal total(@NotNull Token token) {
        BalanceTotal total = new BalanceTotal();
        total.setCharges(new int[5]);
        total.setPays(new int[5]);
        Date now = new Date();
        Date ws = DateTimeUtil.weekStart(now);
        Date we = DateTimeUtil.weekEnd(now);
        Date ms = DateTimeUtil.monthStart(now);
        Date me = DateTimeUtil.monthEnd(now);
        Date ss = DateTimeUtil.seasonStart(now);
        Date se = DateTimeUtil.seasonEnd(now);
        Date ys = DateTimeUtil.yearStart(now);
        Date ye = DateTimeUtil.yearEnd(now);
        balance(total,0,token,now,now);
        balance(total,1,token,ws,we);
        balance(total,2,token,ms,me);
        balance(total,3,token,ss,se);
        balance(total,4,token,ys,ye);
        return total;
    }

    private void balance(BalanceTotal total,int idx,Token token, Date start, Date end){
        Date b = begin(start);
        Date e = end(end);
        total.getCharges()[idx] = chargeOrderService.total(token,b,e);
        total.getPays()[idx] = playRecordService.total(token,b,e);
    }

    private Date begin(@NotNull Date date){
        return DateTimeUtil.setTime(date,0,0,0,0);
    }
    private Date end(@NotNull Date date){
        return DateTimeUtil.setTime(date,23,59,59,999);
    }
}
